package com.lagou.rpc.consumer.handle;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.concurrent.Callable;

/**
 * 客户端处理类
 * 1.发送消息
 * 2.接收消息
 */
public class RpcClientHandler extends SimpleChannelInboundHandler<String> implements Callable {

    /**
     * 通道上下文对象
     */
    private ChannelHandlerContext ctx;

    /**
     * 发送的消息
     */
    private String requestMsg;

    /**
     * 服务端返回的消息
     */
    private String responseMsg;


    public void setRequestMsg(String requestMsg) {
        this.requestMsg = requestMsg;
    }

    /**
     * 通道连接就绪事件
     * @param channelHandlerContext
     */
    @Override
    public void channelActive(ChannelHandlerContext channelHandlerContext) throws Exception{
        ctx = channelHandlerContext;

        //
    }

    /**
     *
     * @param channelHandlerContext
     * @param s
     * @throws Exception
     */
    @Override
    protected synchronized void channelRead0(ChannelHandlerContext channelHandlerContext, String s) throws Exception {
        //服务端返回值
        responseMsg = s;

        //唤醒等待的线程
        notify();

    }

    /**
     * 发送消息到服务端
     * @return
     * @throws Exception
     */
    @Override
    public synchronized Object call() throws Exception {
        //消息发送
        ctx.writeAndFlush(requestMsg);

        //线程等待
        wait();

        return responseMsg;
    }
}

